	//https://webbluetoothcg.github.io/web-bluetooth/#dom-navigator-bluetooth
window.bleLib ={
     uuid:"0000fee7-0000-1000-8000-00805f9b34fb",
		
     uuidls_Service: [
            "00001800-0000-1000-8000-00805f9b34fb",
            "0000ae00-0000-1000-8000-00805f9b34fb",
            "f0020001-0451-4000-b000-000000000000",
            "f0030001-0451-4000-b000-000000000000",
            
            "f0080001-0451-4000-b000-000000000000",
            "f0080002-0451-4000-b000-000000000000",
            "f0080003-0451-4000-b000-000000000000",
            
            '00002902-0000-1000-8000-00805f9b34fb',
            
            "0000fee7-0000-1000-8000-00805f9b34fb",
            "0000180a-0000-1000-8000-00805f9b34fb",
            "00001812-0000-1000-8000-00805f9b34fb"
            ],
    /**检查浏览器是否支持蓝牙 */
    isSupport()
    { 
        if ('bluetooth' in navigator) {
            log('Supported！');
        } else {
            log('Not supported！');
            return false;
        }
        return true;
    },     
    /**
     * 扫描蓝牙
     */
    startScan (){
        navigator.bluetooth.requestDevice({
            filters: [{
                services: [this.uuid]
            }],
            optionalServices: this.uuidls_Service
        })
        .then(device => {
            log('Discovered Devices：' + device.name);
            log('Device status：' + device.gatt.connected);
            log('Device id：' + device.id);
            this.toConenct(device);
        })
        .catch(error => {
            log('Bluetooth Error：' + error);
        });
    },

    /**
     * 配对结果
     */
    async toConenct (device)
    {
        window.cur_ble_device = device;
        if(device.gatt.connected==false)
        {
            device.addEventListener('gattserverdisconnected',this.onDisconnected);
            server = await device.gatt.connect();
            log('Device status：' + device.gatt.connected);
            await window.mgrLib.init(server)
            const customEvent = new Event('gattserverconnected', {
                bubbles: true,  // 事件是否冒泡，默认为 false
                cancelable: true,  // 事件是否可以被取消，默认为 false
              });
            document.dispatchEvent(customEvent);
        }
    },

    toDisconenct()
    {
        if(window.cur_ble_device.gatt.connected)
        {
            window.cur_ble_device.gatt.disconnect();            
        }
    },

    onDisconnected(event)
    {
        log(`bluetooth: ${(window.cur_ble_device && window.cur_ble_device.name) || 'unkwon'} already disconnected`);  
     
        console.log('onDisconnected:',event.target.value);
        const customEvent = new Event('gattserverdisconnected', {
            bubbles: true,  // 事件是否冒泡，默认为 false
            cancelable: true,  // 事件是否可以被取消，默认为 false
            msg:event,
          });
        document.dispatchEvent(customEvent);
    },
};